<template>
  <el-container>
    <el-main>
      <div class="default-main ba-table-box">
        <TableHeader
          :buttons="[
            'refresh',
            'add',
            'edit',
            'remove',
            'comSearch',
            'columnDisplay',
          ]"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" @action="baTable.onTableAction" />
        <!-- 表单 -->
        <PopupForm ref="formRef" v-if="baTable.form.operate" />
      </div>
    </el-main>
  </el-container>
</template>
<script lang="ts" setup>
import { ref, provide, onMounted, markRaw } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff, DictOperation } from "@/utils/common"; // 导入表格api方法生成器
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { WarningItemObject } from "@/api/backend/index";
import { useRoute, useRouter } from "vue-router";
import { useNavTabs } from "@/store/navTabs";
import { useWarningItemObject } from "@/store/backend/Warning/itemObject";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useWarningCategory } from "@/store/backend/Warning/category";
import PopupForm from "./popupForm.vue";
import { useAssetCabinet } from "@/store/backend/Assets/cabinet";
import TagSearch from "./components/tagSearch.vue";

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const route = useRoute();
const router = useRouter();
const navTabs = useNavTabs();
const itemObject = useWarningItemObject();
const dictionary = useDictionary();
const category = useWarningCategory();
const formRef = ref();
const cabinet = useAssetCabinet();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + WarningItemObject)
      ? (navTabs as any).pageSizeMap.get(route.path + WarningItemObject)
      : 10;
  }
  return 10;
};

//初始化字典处理类
const dictOperation = new DictOperation();
//重写字典处理
type dictObj = (arr: any[]) => anyObj;
class NewDictOperation extends DictOperation {
  getDictData: dictObj = (arr: any[]) => {
    let obj: any = {};
    for (let i = 0, len = arr.length; i < len; i++) {
      obj[arr[i].dictLabel] = arr[i].remark;
    }
    return obj;
  };
  //获取字典
  getDictionary = (
    specificClass: any, //pinia仓库类
    dictText: string, //字典名称
    filed: string, //仓库存储的经过处理后的字典对象
    dictStore: string //仓库存储的原始字典数组
  ) => {
    if (
      JSON.stringify(specificClass.tags) == "{}" ||
      !(filed == "" ? true : specificClass.tags[filed]) ||
      JSON.stringify(dictionary.moreTags[dictText]) == "{}"
    ) {
      dictionary.getDictInfo(dictText).then((res: any) => {
        let tempTags = dictOperation.getDictData(res);
        dictionary.moreTags[dictText] = tempTags;
        specificClass.$patch((state: any) => {
          if (filed != "") {
            state.tags[filed] = tempTags;
          }
          state.typeCategoryFormat = this.getDictData(res);
          state[dictStore] = res;
        });
      });
    }
  };
}
const newDictOperation = new NewDictOperation();

//全局事件总线
const { proxy } = useCurrentInstance();
const baTable = new baTableClass(
  new baTableApi(WarningItemObject), //this.api = api菜单管理相关
  {
    pk: "objectId",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("objectName"),
        label: "对象名称",
        prop: "objectName",
        align: "center",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("objectNameVertical"),
        label: "立式机柜别名",
        prop: "objectNameVertical",
        align: "center",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("mqttFiled"),
        label: "MQTT字段名",
        prop: "mqttFiled",
        align: "center",
        operatorPlaceholder: "精确搜索",
      },
      {
        show: filedShowOff("categoryName"),
        label: "类别名称",
        prop: "categoryName",
        align: "center",
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: filedShowOff("unit"),
        label: "单位",
        prop: "unit",
        align: "center",
        operator: false,
      },
      {
        show: false,
        label: "类别ID",
        prop: "categoryId",
        align: "center",
      },
      {
        show: operatorShowOff([route.path + "/edit", route.path + "/remove"]),
        label: "操作",
        align: "center",
        width: "130",
        render: "buttons",
        fixed: "right",
        operator: false,
        buttons: [
          {
            render: "tipButton",
            name: "edit",
            title: "编辑",
            text: "",
            type: "primary",
            icon: "iconfont icon-pencil",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "confirmButton",
            name: "remove",
            title: "删除",
            text: "",
            type: "danger",
            icon: "el-icon-DeleteFilled",
            class: "table-row-delete",
            popconfirm: {
              confirmButtonText: "删除",
              cancelButtonText: "取消",
              confirmButtonType: "danger",
              title: "确定删除所选项吗",
            },
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
      },
    ],
    filter: {
      pageSize: pageSizeKeep(),
    },
  },
  {
    // 默认表单数据(添加)
    defaultItems: {
      cabinetType: 0, //立式
    },
  }
);

onMounted(() => {
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(WarningItemObject);

  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      if (!baTable.activate) return;
      //回滚功能暂无
      if (data.name == "rollback") {
        // onRollback([data.row[baTable.table.pk!]])
      } else if (data.name == "info") {
        //携带主键字段pk
        // infoButtonClick(
        //   (data.row as TableRow)[baTable.table.pk!],
        //   data.row as any
        // );
      }
    }
  );
});

//获取字典
const getDictionary = () => {
  //获取告警类别字典
  newDictOperation.getDictionary(
    itemObject,
    "sys_warning_category",
    "categoryName",
    "typeCategory"
  );
  //获取机柜类型的字典
  dictOperation.getDictionary(
    cabinet,
    "sys_cabinet_type",
    "cabinetType",
    "type"
  );
};
getDictionary();

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);
provide("category", category);
provide("itemObject", itemObject);
provide("cabinet", cabinet);
</script>
<style lang="scss" scoped>
.el-main {
  padding: 0;
}
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
</style>
